<template>
  <div class="search_one">
    <Setting></Setting>
    <el-select
      class="search_text"
      clearable
      v-model="keyword_value"
      filterable
      remote
      reserve-keyword
      placeholder="请输入关键词"
      :remote-method="remoteMethod"
      @change="searchTextChange"
      @clear="clear"
      @blur="blur"
    >
      <el-option
        v-for="item in searchValue"
        :key="item._id"
        :label="item.name"
        :value="item.name"
      >
      </el-option>
    </el-select>
    <el-button type="primary" icon="el-icon-search" @click="handleClick"
      >搜索</el-button
    >
    <el-button type="primary" @click="addUser" v-has="'add'"
      >添加项目</el-button
    >

    <div class="search_two">
      <el-form>
        <el-form-item label="搜索班级">
          <el-select
            v-model="value"
            filterable
            placeholder="请选择"
            @visible-change="classVisible"
            @change="isChange"
          >
            <el-option label="全部" value="all"></el-option>
            <el-option
              v-for="item in option"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>

    <div class="excel">
      <el-button type="success" icon="el-icon-s-management" @click="output"
        >导出excel数据</el-button
      >
    </div>

    <div class="class_pro_table">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="headimgurl" label="头像" width="180">
          <template slot-scope="scope">
            <div class="block">
              <el-avatar
                shape="square"
                :size="50"
                :src="scope.row.headimgurl"
              ></el-avatar>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="class" label="班级"></el-table-column>
        <el-table-column prop="productUrl" label="项目"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              class="btn"
              icon="el-icon-view"
              @click="watcher(row)"
              v-has="'read'"
              >查看</el-button
            >
            <el-button
              type="primary"
              class="btn"
              icon="el-icon-edit"
              @click="editStu(row)"
              v-has="'edit'"
              >编辑</el-button
            >
            <el-button
              type="danger"
              class="btn"
              icon="el-icon-delete"
              @click="deleteStu(row)"
              v-has="'delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="el-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="5"
        :total="lang"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.search_text {
  width: 400px;
  margin-right: 10px;
}

.search_two {
  margin-top: 30px;
}

.search_one >>> .el-table th.is-leaf {
  text-align: center;
}

.search_one >>> .el-table td {
  text-align: center;
}

.excel {
  text-align: right;
  margin: 10px 0;
}

.el-pagination {
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

<script>
import { getUserInfo, searchStu, addUser, delUser, editUser } from "@/api";
import Setting from "@/components/setting";
import excel from "qf-export-excel";

export default {
  data() {
    return {
      value: "",
      keyword_value: "",
      loading: false,
      option: [],
      tableData: [],
      searchValue: [],
      hisvalue: "",
      lang: 0,
      query: "",
    };
  },
  methods: {
    remoteMethod(query) {
      this.hisvalue = query;
      let key = query;
      let count = "";
      let page = "";
      searchStu(page, count, key).then((res) => {
        this.searchValue = res.data.data;
      });
    },
    updateStuTable(params = { count: 5, page: 1, classes: "" }) {
      //发送请求获取学员数据
      this.loading = true;
      getUserInfo(params).then((res) => {
        //获取数据成功
        this.tableData = res.data.data;
        //关闭loading
        this.loading = false;
      });
    },
    searchTextChange(searchtext) {
      this.tableData = this.searchValue;

      // 重新渲染分页
      getUserInfo({
        page: "",
        count: this.tableData.length,
        classess: "",
      }).then((res) => {
        this.lang = res.data.data.length;
      });
    },
    clear() {
      console.log("清除");
      this.updateStuTable();
      this.hisvalue = "";

      this.page();
    },
    blur() {
      this.keyword_value = this.hisvalue;
    },
    handleClick() {
      let v = this.keyword_value;
      let count = "";
      let page = "";
      searchStu(page, count, v).then((res) => {
        this.tableData = res.data.data;
      });

      // 重新渲染分页
      getUserInfo({
        page: "",
        count: this.tableData.length,
        classess: "",
      }).then((res) => {
        this.lang = res.data.data.length;
      });
    },
    classVisible(isVisible) {
      if (isVisible) {
        let params = { count: "", page: "", classes: "" };
        getUserInfo(params).then((res) => {
          //去重
          let norepeatArr = [];
          res.data.data.forEach((item) => {
            norepeatArr.push(item.class);
          });
          norepeatArr = Array.from(new Set(norepeatArr));
          this.option = norepeatArr;
        });
      }
    },
    isChange(query) {
      if (query === "all") {
        this.updateStuTable();
        this.page();
      } else {
        console.log(query);
        let classes = query === "all" ? "" : query;
        //复用更新学员数据的方法
        let obj = { page: 1, count: 10, classes };
        this.updateStuTable(obj);

        getUserInfo(obj).then((res) => {
          this.lang = res.data.data.length;
        });
      }
    },
    // 切换分页时触发
    handleCurrentChange(query) {
      // 储存分页
      this.query = query;
      let config = {
        page: query,
        count: 5,
        classess: "",
      };
      getUserInfo(config).then((res) => {
        this.tableData = res.data.data;
      });
    },
    // 添加项目按钮
    addUser() {
      let obj = {
        isShow: true,
        options: "add",
        title: "新增学员信息",
      };
      this.$bus.$emit("isShow", obj);
      // console.log("点击新增");
    },
    // 编辑用户
    editStu(row) {
      // console.log("点击编辑");
      let obj = {
        isShow: true,
        options: "edit",
        title: "编辑学员信息",
        row,
      };
      // 1、把显示信息发送到表单组件
      this.$bus.$emit("editShow", obj);

      // 2、这边发送请求更新视图
      this.$bus.$on("action", (data) => {
        editUser(data).then((res) => {
          if (res.data.state) {
            // 更新视图
            this.updateStuTable();

            // 提示消息
            this.$message({
              type: "success",
              message: "更新成功!",
            });
          }
        });
      });
    },
    // 删除操作
    deleteStu(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 根据sid删除用户
          let sid = row.sId;
          delUser(sid).then((res) => {
            if (res.data.state) {
              // 更新视图
              this.updateStuTable();
              // 重新渲染分页
              this.page();
              // 提示消息
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: "删除失败",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 查看学员信息
    watcher(row) {
      this.$router.push({ name: "studentProfile", query: { sId: row.sId } });
    },
    // 重新渲染分页
    page() {
      getUserInfo({ page: "", count: "", classes: "" }).then((res) => {
        this.lang = res.data.data.length;
      });
    },
    // 导出excel表格
    output() {
      getUserInfo({ page: this.query, count: 5, classes: "" }).then((res) => {
        console.log(res);
        let titleList = [
          {
            title: "头像",
            key: "headimgurl",
          },
          {
            title: "姓名",
            key: "name",
          },
          {
            title: "班级",
            key: "class",
          },
          {
            title: "项目",
            key: "productUrl",
          },
        ];

        let dataSource = [];
        res.data.data.map((item) => {
          let obj = {
            headimgurl: item.headimgurl,
            name: item.name,
            class: item.class,
            productUrl: item.productUrl,
          };
          dataSource.push(obj);
          return dataSource;
        });

        // console.log(dataSource);
        excel(titleList, dataSource, "学员数据表");
      });
    },
  },
  created() {
    // 重新渲染表格
    this.updateStuTable();
    // 重新渲染分页
    this.page();
  },
  components: {
    Setting,
  },
  mounted() {
    this.$bus.$on("updata", (data) => {
      // console.log(data);
      // 往服务器添加信息
      addUser(data).then((res) => {
        if (res.data.state) {
          // 提示消息
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.updateStuTable();
        } else {
          // 提示消息
          this.$message({
            type: "error",
            message: "添加失败!",
          });
        }
      });
    });
  },
};
</script>
